<?php

namespace App\Http\ApiControllers;

use App\Models\Application;
use App\Models\Order;
use Closure;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\RuntimeException;
use EasyWeChat\Pay\Message;
use Illuminate\Http\Request;
use Psr\Http\Message\ResponseInterface;
use ReflectionException;
use Throwable;

class NotifyController extends ApiController
{
    /**
     * Notes   : 支付结果回调
     *
     * @Date   : 2024/7/18 下午5:24
     * @Author : <Jason.C>
     * @param  Request  $request
     * @param  string  $appKey
     * @return ResponseInterface
     * @throws InvalidArgumentException
     * @throws RuntimeException
     * @throws ReflectionException
     * @throws Throwable
     */
    public function wechat(Request $request, string $appKey): ResponseInterface
    {
        $app = Application::ofEnabled()->where('app_key', $appKey)->first();
        $payment = $app->wechat->payment->init();
        $server = $payment->getServer();
        $server->handlePaid(function (Message $message, Closure $next) use ($payment) {
            $outTradeNo = $message->out_trade_no;
            $response = $payment->getClient()->get("v3/pay/transactions/out-trade-no/$outTradeNo", [
                'query' => [
                    'mchid' => $payment->getMerchant()->getMerchantId(),
                ],
            ]);

            $resource = $response->toArray();

            #todo 确认查询信息，因为目前还没有支付等待测试
            $order = Order::where('out_trade_no', $outTradeNo)->first();
            $order->paid($resource);

            return $next($message);
        });

        return $server->serve();
    }

    /**
     * Notes   : 退款结果回调
     *
     * @Date   : 2024/7/19 下午5:38
     * @Author : <Jason.C>
     */
    public function refund()
    {
    }
}
